<?php
// +----------------------------------------------------------------------
// | Created by Sublime: [ Conqweal ]
// +----------------------------------------------------------------------
// | Copyright (c) 2021~20223[chenjia] All rights reserved.
// +----------------------------------------------------------------------
// | SiteUrl: http://www.99dn.cn
// +----------------------------------------------------------------------
// | Author: Conqweal <150672834@qq.com>
// +----------------------------------------------------------------------
// | Date: 2021/12/22 0026
// +----------------------------------------------------------------------
// | Description:信息分类
// +----------------------------------------------------------------------

namespace app\admin\controller;

use app\admin\model\Cat as cmodel;
use think\facade\Cache;
use support\Request;
use think\facade\Db;
use support\Util\InitTree;
use app\BackendController;

class CatController extends BackendController
{

    var  $group='文章';


    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index(Request $request)
    {
        $pid = $request->get('pid/d', 0);
        return view('cat/index', compact("pid"));
    }

    public function listData(Request $request)
    {
       
        $pid = $request->get('pid/d', 0);
        $w     = [           
            ['group', '=', $this->group],
        ];
        if ($request->get('cat_name')) {
            $w[] = ['b.cat_name', 'like', '%' . $request->get('cat_name') . '%'];

        }
        if($pid){
             $w[] = ['a.pid', '=', $pid];
        }

        $q = cmodel::alias('a')->join("cat_description b", "a.cat_id=b.cat_id and b.language_id=" . $this->lang_id, 'left')->where($w);
        $ls = $q->field("a.cat_id,a.pid,b.cat_name,a.cat_id as id,a.pid as parentid,b.cat_name as name")->select()->toArray();
        
        $ls = array_column($ls,null, "id");   
        $tree = new InitTree;
        $tree->set_tree($ls);  
        $ls = $tree->get_childs(0);   
        $ls = array_values($ls);
        return json(['code' => count($ls) > 0 ? 0 : 201, 'msg' => '无数据', 'count' => count($ls), 'data' => $ls]);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {

        $menus = cmodel::with("description")->where('group',$this->group)->select();
        $pid  =request()->get("pid");
        $cat_options = '';
        if (!$menus->isEmpty()) {
            $menus_new = [];
            foreach ($menus as $k => $v) {

                $menus_new[$v['cat_id']] = [
                    'id'       => $v['cat_id'],
                    'parentid' => $v['pid'],                   
                    'order'    => $v['sorted'],
                    'name'     => $v->description[0]->cat_name,
                ];
            }

            $tree = new InitTree;
            $tree->set_tree($menus_new);

            $cat_options = $tree->get_tree(0, $pid);

        }

        $langs = getLangs();

        return view('cat/create', compact('cat_options', 'langs'));
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $post  = $request->post();
        $valid = new \app\admin\validate\Cat;
        $r     = $valid->check($post);
        if (!$r) {
            $msg = ['status' => -1, 'msg' => $valid->getError()];
        } else {
            $cmodel = new cmodel;
            $post['group'] = $this->group;
            $cmodel->save($post);
            $id = $cmodel->cat_id;
            //多语言处理

            array_walk($post['description'], function (&$v, $k) use ($id) {
                $v['cat_id']      = $id;
                $v['language_id'] = $k;
            });

            $cmodel->description()->saveAll($post['description']);
            $cmodel->save($post);

            $msg = ['status' => 1, 'msg' => '保存成功'];
        }
        return json($msg);
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit(Request $request)
    {
        $id = $request->get("id");
        $data        = cmodel::with("description")->find($id);
        $description = array_column($data['description']->toArray(), null, 'language_id');
        $menus     = cmodel::with("description")->where('group',$this->group)->select();   
        $menus_new = [];
        foreach ($menus as $k => $v) {
            $menus_new[$v['cat_id']] = [
                'id'       => $v['cat_id'],
                'parentid' => $v['pid'],
                'order'    => $v['sorted'],
                'name'     => $v->description[0]->cat_name,
            ];
        }
               
        $tree = new InitTree;
        $tree->set_tree($menus_new);

        $cat_options = $tree->get_tree(0, $data->pid);

        $langs = getLangs();

        return view('cat/edit', compact('data', 'cat_options', 'langs', 'description'));
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request)
    {
        $id = $request->get("id");
        $post   = $request->post();
        $valid  = new \app\admin\validate\Cat;
        $r      = $valid->check($post);
        $cmodel = new cmodel;
        $main   = $cmodel->where('cat_id', $id)->find();
        if (!$r) {
            $msg = ['status' => -1, 'msg' => $valid->getError()];
        } else {

            //多语言处理
            $main->description()->where("cat_id", $id)->delete();
            array_walk($post['description'], function (&$v, $k) use ($id) {
                $v['cat_id']      = $id;
                $v['language_id'] = $k;
            });

            $main->description()->saveAll($post['description']);
            $post['group'] = $this->group;
            $main->save($post);

            $msg = ['status' => 1, 'msg' => '保存成功'];
        }
        return json($msg);
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete(Request $request)
    {   
        $id = $request->get("id");
        $ids = is_string($id) ? explode(",", $id) : $id;
        foreach ((array) $ids as $id) {
            $f = Db::name('info_cat')->where('cat_id',$id)->count();
            if($f>0){
                return $this->error('存在数据，不能删除');
            }

            $info = cmodel::with(['description'])->find($id);
            $info->together(['description'])->delete();
            unset($info);
        }

        return json(['msg' => '删除成功', 'status' => 1]);
    }
}
